package com.sky.sqlSession;

import com.sky.executor.Executor;
import com.sky.pojo.Configuration;
import com.sky.pojo.MappedStatement;

import java.util.List;

/**
 * @Description
 * @Author gaotianzhi
 * @Date 2023-10-31 16:47
 */
public class DefaultSqlSession implements SqlSession {

    private Executor executor;
    private Configuration configuration;

    public DefaultSqlSession(Executor executor, Configuration configuration) {
        this.executor = executor;
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId) throws Exception {
        return selectList(statementId, null);
    }

    @Override
    public <E> List<E> selectList(String statementId, Object parameter) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<E> list = executor.query(configuration, mappedStatement, parameter);
        return list;
    }

    @Override
    public <T> T selectOne(String statementId, Object parameter) throws Exception {
        List<Object> objects = selectList(statementId, parameter);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else if (objects.size() > 1) {
            throw new RuntimeException("结构大于1条！");
        } else {
            return null;
        }

    }
}
